package db

import (
	"errors"
	"fmt"
	"gitee.com/ling1314/origin-utility/model"
	"gorm.io/gorm"
)

func Run() {
	type vector[T any] []T

	list := vector[interface{}]{
		&model.User{},
		&model.UserExtend{},
		&model.Dept{},
		&model.Role{},
		&model.AppHost{},
		&model.Cluster{},
		&model.AppInstall{},
		&model.AppIssue{},
		&model.MapDirectApp{},
		&model.MapDeptApp{},
		&model.MapUserRole{},
		&model.HostSession{},
		&model.Property{},
		&model.MapHostSessionForApp{},
		&model.Topology{},
		&model.MiaoClient{},

		&model.IdpWarnLoad{},
		&model.IdpWarnHostname{},

		&model.IdpLogCpu{},
		&model.IdpLogMemory{},
		&model.IdpLogDisk{},
		&model.IdpLogBoard{},
		&model.IdpLogSysAbstract{},
		&model.IdpLogApp{},
		&model.IdpAppChangeLog{},

		&model.IdpOrg{},
		&model.IdpOrgMapUser{},
		&model.IdpOrgMapDevice{},
		&model.IdpOrgPoint{},

		//&model.Credential{},
		//&model.Gateway{},
		//&model.MapAppDept{},
		//
		//&model.MiaoClientLog{},
	}
	// 初始化数据库表结构
	for _, item := range list {
		if !db.Migrator().HasTable(item) {
			err := db.AutoMigrate(item)
			if err != nil {
				panic(fmt.Errorf("初始化数据库表结构异常: %v", err.Error()))
			}
		}
	}

	initUser()
	initRole()
	initUserMapRole()
	initDept()
	initCluster()
}

func initCluster() {
	var (
		err error
		d   model.Cluster
	)
	if err = db.Model(&model.Cluster{}).Where("cluster_id = 1 ").First(&d).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		d = model.Cluster{
			ClusterId:       1,
			Name:            "默认集群",
			CpuThreshold:    90,
			MemoryThreshold: 90,
			TimeOutAction:   1,
			MaxSessionTime:  60,
			MaxTimeOutTime:  60,
			Creator:         "root",
			CreatorId:       1,
		}
		if db.Create(&d).Error != nil {
			panic(fmt.Sprintf("导入初始集群信息时发生错误：%v", err))
		}
	}

}

func initUser() {
	var (
		err error
	)
	var d model.User
	if err = db.Where("user_id = ?", model.RootId).First(&d).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		err = db.Create(model.RootUser).Error
		if err != nil {
			panic(fmt.Sprintf("导入初始化用户信息时发生错误：%v", err))
		}
		mut := model.UserExtend{
			UserId: model.RootId,
		}
		err = db.Create(&mut).Error
		if err != nil {
			panic(fmt.Sprintf("导入初始化sql信息时发生错误：%v", err))
		}
	}
}

func initRole() {
	var (
		err error
	)
	var t int64
	if err = db.Where("role_id = in (1,2,3)").Count(&t).Error; err != nil || t != 3 {
		err = db.Save(&model.DefaultRoles).Error
		if err != nil {
			panic(fmt.Sprintf("导入初始化角色信息时发生错误：%v", err))
		}
	}
}

func initUserMapRole() {
	var err error
	mus := model.MapUserRole{
		UserId: 1,
		RoleId: 1,
	}
	var d model.MapUserRole
	if err = db.Model(&model.MapUserRole{}).Where("user_id = ? and role_id = ?", mus.UserId, mus.RoleId).First(&d).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		err = db.Create(&mus).Error
		if err != nil {
			panic(fmt.Sprintf("导入初始化sql信息时发生错误：%v", err))
		}
	}
}

func initDept() {
	var err error

	var n int64
	db.Model(&model.Dept{}).Where("dept_id in ?", []int64{model.DeptIdForRoot, model.DeptIdForNothing}).Count(&n)
	if n != 2 {
		err = db.Create(&model.DefaultDept).Error
		if err != nil {
			panic(fmt.Sprintf("导入初始化sql信息时发生错误：%v", err))
		}
	}
}
